import { loginApi, getUserProfileApi, getEmployeeApi } from "@/api/user";
import { resetRouter } from "@/router";
import { getToken, setToken, removeToken } from "@/utils/auth";

const state = () => {
  return {
    // 用户令牌
    // 刷新页面时，从本地取token,借助逻辑或短路
    token: getToken() || "",
    // 用户信息
    userInfo: {},
  };
};

const mutations = {
  // 设置token
  setToken: (state, token) => {
    state.token = token;
    setToken(token);
  },
  // 获取用户信息
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  // 清空token
  removeToken: (state) => {
    state.token = "";
    removeToken("");
  },
  // 清空用户信息
  removeUserInfo: (state) => {
    state.userInfo = {};
  },
};

const actions = {
  // 登录action
  loginActions: async ({ commit }, loginForm) => {
    // 发起登录请求
    const resp = await loginApi(loginForm);
    // console.log(resp);
    commit("setToken", resp.data);
  },
  // 获取用户信息
  getUserInfoActions: async ({ commit }) => {
    const resp = await getUserProfileApi();
    // console.log(resp);
    // 基于此次接口返回的userId继续发请第2次请求(获取用户头像等信息)
    const { userId } = resp.data;
    const { data } = await getEmployeeApi(userId);
    // console.log(data);
    commit("setUserInfo", { ...data, ...resp.data });
    // return { ...data, ...resp.data };
  },
  loginutAction: ({ commit }) => {
    commit("removeToken");
    commit("removeUserInfo");
    // 3. 重置路由
    resetRouter();
    // 4. 重置 vuex 中的路由信息
    //root:true 从全局出发
    commit("route/removeRoutes", [], { root: true });
    commit(
      "settings/CHANGE_SETTING",
      { key: "theme", value: "#3d6df8" },
      { root: true }
    );
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
